package logic

import (
	"context"
	"fmt"
	"house_srv/house"
	"net/http"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AlipayNotifyLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAlipayNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AlipayNotifyLogic {
	return &AlipayNotifyLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AlipayNotifyLogic) AlipayNotify(w http.ResponseWriter, r *http.Request) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	fmt.Println("触发了支付宝回调")
	fmt.Println(r.FormValue("out_trade_no"))
	fmt.Println(r.FormValue("trade_status"))
	fmt.Println("触发了支付宝回调")
	//枚举名称	枚举说明
	//WAIT_BUYER_PAY	交易创建，等待买家付款。
	//TRADE_CLOSED	未付款交易超时关闭，或支付完成后全额退款。
	//TRADE_SUCCESS	交易支付成功。
	//TRADE_FINISHED	交易结束，不可退款。
	tradeStatus := r.FormValue("trade_status")
	orderSn := r.FormValue("out_trade_no")

	var OrderStatus int

	if tradeStatus == "TRADE_SUCCESS" {
		OrderStatus = 2
		l.svcCtx.HouseSrv.UpdateOrder(l.ctx, &house.UpdateOrderRequest{
			OrderSn:     orderSn,
			OrderStatus: int64(OrderStatus),
		})
	} else if tradeStatus == "TRADE_FINISHED" {
		OrderStatus = 4
		l.svcCtx.HouseSrv.UpdateOrder(l.ctx, &house.UpdateOrderRequest{
			OrderSn:     orderSn,
			OrderStatus: int64(OrderStatus),
		})
	} else if tradeStatus == "TRADE_CLOSED" {
		OrderStatus = 5
		l.svcCtx.HouseSrv.UpdateOrder(l.ctx, &house.UpdateOrderRequest{
			OrderSn:     orderSn,
			OrderStatus: int64(OrderStatus),
		})
	} else {
		return
	}
	fmt.Println(w.Write([]byte("SUCCESS")))
	return
}
